package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    private final StringRedisTemplate stringRedisTemplate;

    public ShopTypeServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public Result queryAllShop() {
        //1、先查询redis有没有缓存商铺
        String shopType = stringRedisTemplate.opsForValue().get("shop_type");

        //2、存在，直接返回
        if(StrUtil.isNotBlank(shopType)){
            List<ShopType> list = JSONUtil.toList(shopType, ShopType.class);
            return Result.ok(list);
        }

        //3、不存在，访问数据库
        List<ShopType> shopTypes = list();

        //4、数据库不存在
        if(shopTypes == null){
            return Result.fail("没有数据！");
        }

        //5、数据库存在，写入缓存
        stringRedisTemplate.opsForValue().set("shop_type",JSONUtil.toJsonStr(shopTypes));

        //6、返回
        return Result.ok(shopTypes);
    }
}
